package com.rxsk.cas.filter;


import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import static com.rxsk.cas.constant.SessionConstants.*;
import static com.rxsk.cas.constant.SessionConstants.AUTHORIZATION;

@Slf4j
public class ShiroLoginFilter extends FormAuthenticationFilter {

    /**
     * 在访问controller前判断是否登录，返回json，不进行重定向。
     * @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String token =  WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        log.debug("header token ： " + token);
        if(isLoginRequest(request, response)){
            return executeLogin(request, response);
        }else{
            saveRequestAndRedirectToLogin(request, response);
            return false;
        }
        /*HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        if(StringUtils.isEmpty(token)){
            Response resultData = Response.builderFailed(TokenErrorEnum.CODE_ERROR_USER_NOT_LOGIN);
            resultData.setMessage("token 不能为空");
            httpServletResponse.getWriter().write(JSONObject.toJSON(resultData).toString());
            return false;
        }

        if(!JwtTokenUtils.validateToken(token, secretKey)){
            Response resultData = Response.builderFailed(TokenErrorEnum.TOKEN_VALID_ERROR);
            resultData.setMessage("token 验证错误");
            httpServletResponse.getWriter().write(JSONObject.toJSON(resultData).toString());
            return false;
        }*/

    }

    @Bean
    public FilterRegistrationBean registration(ShiroLoginFilter filter) {
        FilterRegistrationBean registration = new FilterRegistrationBean(filter);
        registration.setEnabled(false);
        return registration;
    }


}